<?php

namespace app\common\model;

use think\Controller;
use think\Db;
use think\Env;
use think\Log;
use GuzzleHttp\Client;

class Wxpay extends Controller
{
    //微信app登录
    public static function wxAppLogin($code)
    {
        $appid =  'wxd34dfb096708edde';
        $secret =  '8460b3fa982de157b5fa49e25e2a0a92';
        $url = 'https://api.weixin.qq.com/sns/oauth2/access_token?appid=' . $appid . '&secret=' . $secret . '&code=' . $code . '&grant_type=authorization_code';
        $response =  file_get_contents($url);
        $callback = json_decode($response, true);
        return $callback;
    }
    // private $config = array(
    //     //商户号
    //     'mchid' => '',
    //     //应用ID,您的APPID。*
    //     'appid' => "",
    //     //异步通知地址*
    //     'notify_url' => "",
    //     //商户私钥*
    //     'apiv3_private_key' => "",
    //     //证书序列号
    //     'xlid' => '',
    //     //退款回调地址
    //     'refund_notify_url' => "",
    // );

    //统一下单
    public static function wxpay($out_trade_no, $money, $openid, $attach)
    {
        if (Env::get('app.debug') == true) {
            $money = 0.01;
        }
        if (empty($out_trade_no)) return json(['code' => 202, 'msg' => '缺少参数order_sn']);
        // 官方提供网址
        $url = "https://api.mch.weixin.qq.com/v3/pay/transactions/app";
        // $urlarr = parse_url($url); //拆解为：[scheme=>https,host=>api.mch.weixin.qq.com,path=>/v3/pay/transactions/native]
        $time = time(); //时间戳
        $noncestr = self::getNonceStr();
        $appid = config('site.app_id'); //appID
        $mchid = config('site.mch_id'); //商户ID
        $data = array();
        $data['appid'] = $appid;
        $data['mchid'] = $mchid;
        $data['attach'] = $attach;
        $data['description'] = '商品描述'; //商品描述
        $data['out_trade_no'] = $out_trade_no; //订单编号，订单号在微信支付里是唯一的
        $data['notify_url'] =  cdnurl(config('site.notify_url'), true); //需根据自己的情况修改回调接口，也可以为空
        $data['amount']['total'] = $money * 100; //金额 单位 分
        $data['scene_info']['payer_client_ip'] = $_SERVER["REMOTE_ADDR"];; //场景ip
        $data['payer']['openid'] = $openid; //openid
        $data = json_encode($data);
        Log::write($data);
        //向微信接口地址提交json格式的$data和header的头部信息，得到返回值
        $res = self::curl_post_https($url, $data);
        $prepay_id = json_decode($res, true)['prepay_id'];
        $paySign = self::getWechartSign($appid, $time, $noncestr, 'prepay_id=' . $prepay_id);
        $payData = [
            'timeStamp' => (string) $time,
            'nonceStr' => $noncestr,
            'package' => 'prepay_id=' . $prepay_id,
            'signType' => 'RSA',
            'paySign' => $paySign
        ];
        return $payData;
    }

    //获取随机字符串
    public static function getNonceStr()
    {
        $strs = "QWERTYUIOPASDFGHJKLZXCVBNM1234567890";
        $name = substr(str_shuffle($strs), mt_rand(0, strlen($strs) - 11), 32);
        return $name;
    }

    //微信支付签名
    public static function getSign($data = array(), $url, $randstr, $time)
    {
        $str = "POST" . "\n" . $url . "\n" . $time . "\n" . $randstr . "\n" . $data . "\n";
        $key = file_get_contents(ROOT_PATH  . str_replace('/', DS, substr('/application/certs/apiclient_key.pem', 1))); //在商户平台下载的秘钥,读取到变量
        $str = self::getSha256WithRSA($str, $key);
        return $str;
    }

    //调起支付的签名
    public static function getWechartSign($appid, $timeStamp, $noncestr, $prepay_id)
    {
        $str = $appid . "\n" . $timeStamp . "\n" . $noncestr . "\n" . $prepay_id . "\n";
        $key = file_get_contents(ROOT_PATH . str_replace('/', DS, substr('/application/certs/apiclient_key.pem', 1))); //在商户平台下载的秘钥,读取到变量
        $str = self::getSha256WithRSA($str, $key);
        return $str;
    }

    //加密
    public static function getSha256WithRSA($content, $privateKey)
    {
        $binary_signature = "";
        $algo = "sha256WithRSAEncryption";
        openssl_sign($content, $binary_signature, $privateKey, $algo);
        $sign = base64_encode($binary_signature);
        return $sign;
    }
    //明文加密
    public static  function getEncrypt($str) {
        //$str是待加密字符串 
        $public_key = file_get_contents(ROOT_PATH . str_replace('/', DS, substr('/application/certs/apiclient_key.pem', 1))); //在商户平台下载的秘钥,读取到变量
        $encrypted = '';
        if (openssl_public_encrypt($str, $encrypted, $public_key, OPENSSL_PKCS1_OAEP_PADDING)) {
            //base64编码 
            $sign = base64_encode($encrypted);
        } else {
            return 'encrypt failed';
        }
        return $sign;
    } 
    /* PHP CURL HTTPS POST */
    public static function curl_post_https($url, $data)
    {
        $urlarr = parse_url($url);
        $time = time();
        $mchid = config('site.mch_id'); //商户ID
        $xlid = config('site.serial_no'); //证书序列号
        $refundData = json_encode($data, JSON_UNESCAPED_SLASHES | JSON_UNESCAPED_UNICODE);
        $nonce = self::getNonceStr();
        $key = self::getSign($refundData, $urlarr['path'], $nonce, $time);
        $token = sprintf('mchid="%s",serial_no="%s",nonce_str="%s",timestamp="%d",signature="%s"', $mchid, $xlid, $nonce, $time, $key);
        $header  = array(
            'Accept: application/json',
            'Content-Type: application/json; charset=utf-8',
            'User-Agent:*/*',
            'Authorization: WECHATPAY2-SHA256-RSA2048 ' . $token
        );
        // 模拟提交数据函数
        $curl = curl_init(); // 启动一个CURL会话
        curl_setopt($curl, CURLOPT_URL, $url); // 要访问的地址
        curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, 0); // 对认证证书来源的检查
        curl_setopt($curl, CURLOPT_SSL_VERIFYHOST, 0); // 从证书中检查SSL加密算法是否存在，如果出错则修改为0，默认为1
        curl_setopt($curl, CURLOPT_USERAGENT, $_SERVER['HTTP_USER_AGENT']); // 模拟用户使用的浏览器
        curl_setopt($curl, CURLOPT_FOLLOWLOCATION, 1); // 使用自动跳转
        curl_setopt($curl, CURLOPT_AUTOREFERER, 1); // 自动设置Referer
        curl_setopt($curl, CURLOPT_POST, 1); // 发送一个常规的Post请求
        curl_setopt($curl, CURLOPT_POSTFIELDS, $data); // Post提交的数据包
        curl_setopt($curl, CURLOPT_TIMEOUT, 30); // 设置超时限制防止死循环
        curl_setopt($curl, CURLOPT_HEADER, 0); // 显示返回的Header区域内容
        curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1); // 获取的信息以文件流的形式返回
        curl_setopt($curl, CURLOPT_HTTPHEADER, $header);
        $tmpInfo = curl_exec($curl); // 执行操作
        if (curl_errno($curl)) {
            echo 'Errno' . curl_error($curl); //捕抓异常
        }
        curl_close($curl); // 关闭CURL会话
        return $tmpInfo; // 返回数据，json格式
    }

    //退款
    public static function refund($id)
    {

        //商户订单号,微信生成的退款订单号 二选一即可
        $order = Order::get($id);
        if (Env::get('app.debug') == true) {
            $order['pay_money'] = 0.01;
        }
        $out_refund_no = sn('order', 'out_refund_no', 'RF');
        $refundData = [
            'out_refund_no' => $out_refund_no,
            'reason' => '商品退款',

            'notify_url' => cdnurl(config('site.refund_notify'), true),
            'funds_account' => 'AVAILABLE',
            'amount' => [
                'refund' => floatval($order['pay_money']) * 100, //退款标价金额，单位为分，可以做部分退款
                'total' => floatval($order['pay_money']) * 100, //订单总金额，单位为分
                'currency' => 'CNY'
            ]
        ];
        $refundData['transaction_id'] = $order['transaction_id'];
        $url = 'https://api.mch.weixin.qq.com/v3/refund/domestic/refunds';
        $refundData = json_encode($refundData);
        $res = self::curl_post_https($url, $refundData);
        $res_array = json_decode($res, true);
        if (isset($res_array['status']) && ($res_array['status'] == 'PROCESSING' || $res_array['status'] == 'SUCCESS') && isset($res_array['status'])) {
        } else {
            exception($res_array['message']);
        }
    }

    public static function withdrawal($amount, $openid)
    {

        $batch_name   = 'GR积分提现'; //转账的名称
        $money = (int)($amount * 100); // 提现金额
        $trade_no = 'yetx' . date('Ymd') . mt_rand(1000, 9999); //提现编号
        $appid = config('site.wx_appid'); //appID
        $post_data = [
            "appid" => $appid, //appid
            "out_batch_no" => $trade_no, //商家批次单号
            "batch_name" => $batch_name, //批次名称
            "batch_remark" => $batch_name, //批次备注
            "total_amount" => $money, // 转账金额单位为“分”
            "total_num" => 1, // 转账总笔数
            //此处可以多笔提现  组合二维数组放到transfer_detail_list即可   
            "transfer_detail_list" => [
                [
                    'out_detail_no' => $trade_no,
                    'transfer_amount' => $money,
                    'transfer_remark' => $batch_name,
                    'openid' => $openid,
                ]
            ]
        ];

        $url = 'https://api.mch.weixin.qq.com/v3/transfer/batches';
        //JSON_UNESCAPED_SLASHES|JSON_UNESCAPED_UNICODE  防止中文被转义
        $post_data = json_encode($post_data);

        $result = self::curl_post_https($url, $post_data);
        $result = json_decode($result, true);
        if (isset($result['prepay_id'])) {
            return $result['prepay_id'];
        }
        return $result;
    }
}
